"""
构建exe可执行文件的脚本
Author: AI Assistant
Date: 2025-01-09
"""
import os
import sys
import subprocess
from pathlib import Path

def build_exe():
    """构建exe可执行文件"""
    
    # 项目根目录
    project_root = Path(__file__).parent
    src_dir = project_root / "src"
    
    # PyInstaller命令
    cmd = [
        "pyinstaller",
        "--onefile",  # 打包成单个exe文件
        "--windowed",  # 不显示控制台窗口
        "--name=实验报告批改系统",
        "--icon=icon.ico",  # 如果有图标文件
        "--add-data=src;src",  # 添加src目录到exe中
        "--hidden-import=tkinter",
        "--hidden-import=tkinter.ttk",
        "--hidden-import=tkinter.filedialog",
        "--hidden-import=tkinter.messagebox",
        "--hidden-import=tkinter.scrolledtext",
        "--hidden-import=docx",
        "--hidden-import=openpyxl",
        "--hidden-import=pandas",
        "--hidden-import=requests",
        "--hidden-import=lxml",
        "--hidden-import=tqdm",
        "--hidden-import=PIL",
        "--hidden-import=openai",
        "src/gui_app.py"
    ]
    
    print("开始构建exe文件...")
    print(f"命令: {' '.join(cmd)}")
    
    try:
        # 切换到项目根目录
        os.chdir(project_root)
        
        # 执行PyInstaller命令
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        
        print("构建成功!")
        print("exe文件位置: dist/实验报告批改系统.exe")
        
    except subprocess.CalledProcessError as e:
        print(f"构建失败: {e}")
        print(f"错误输出: {e.stderr}")
        return False
    except FileNotFoundError:
        print("错误: 未找到PyInstaller，请先安装: pip install pyinstaller")
        return False
    
    return True

def install_dependencies():
    """安装依赖"""
    print("安装依赖包...")
    
    dependencies = [
        "pyinstaller",
        "python-docx",
        "requests",
        "lxml",
        "openpyxl",
        "pandas",
        "tqdm",
        "Pillow",
        "openai"
    ]
    
    for dep in dependencies:
        try:
            subprocess.run([sys.executable, "-m", "pip", "install", dep], check=True)
            print(f"✓ {dep}")
        except subprocess.CalledProcessError:
            print(f"✗ {dep} 安装失败")

if __name__ == "__main__":
    print("=" * 50)
    print("实验报告批改系统 - 构建exe文件")
    print("=" * 50)
    
    # 安装依赖
    install_dependencies()
    
    # 构建exe
    if build_exe():
        print("\n构建完成! 可以在dist目录中找到exe文件。")
    else:
        print("\n构建失败，请检查错误信息。")
